package com.hongri.recyclerview.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.hongri.recyclerview.service.HongriServiceImpl;
import com.hongri.recyclerview.service.TestService;
import com.hongri.recyclerview.utils.Logger;
import com.hongri.recyclerview.utils.ToastUtil;

/**
 * @author：zhongyao on 2016/7/29 11:14
 * @description:
 */
public class WelcomeActivity extends BaseActivity {
    private String action = "com.hongri.recyclerview.MAINACTIVITY";
    private String category = "com.hongri.recyclerview.MAINN";
    //private String uriString = "hongri://recyclerview/mainactivity";
    private String uriString = "hongri_new://recyclerview_new/mainactivity_new?name=hongri";
    public static String broadAction = "com.hongri.recyclerview.BROADCAST";
    private int requestCode = 0;
    private Intent service, intentService;
    private TestService testService;
    private BroadcastReceiver receiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 实例化HongriService
         */
        HongriServiceImpl.getInstance();
        //        ArticlesProvider provider = new ArticlesProvider();
        /**
         *隐式启动Activity：
         * http://fenglingdangyang.blog.sohu.com/231856618.html
         *
         * 1、隐士启动的Activity的AndroidManifest.xml文件中必须写该行：
         * <category android:name="android.intent.category.DEFAULT"/>
         * 否则会报错。
         * 例外情况是：android.intent.category.MAIN和android.intent.category.LAUNCHER的filter中
         * 没有必要加入android.intent.category.DEFAULT，当然加入也没有问题。
         *
         * 2、AndroidManifest.xml文件中查找到符合这个 intentFilter 的就启动这个Activity，
         * 如果有多个这样的Activity符合条件的话，就跳出一个对话框让用户选择究竟要启动哪一个。
         *
         * 3、单单靠添加addCategory属性不能匹配（必须有action属性）
         *
         * 4、单单靠添加setData属性不能添加（必须有action属性）
         *
         * 5、Uri的格式:scheme://host:port/path or pathPrefix or pathPattern
         */

        Intent intent = new Intent(action);
        Bundle bundle = new Bundle();
        bundle.putString("name", "hongri");
        bundle.putString("age", "28");
        intent.putExtras(bundle);
        intent.addCategory(category);

        /**
         * 从uri中获取参数
         */
        Uri uri = Uri.parse(uriString);
        String name = uri.getQueryParameter("name");
        ToastUtil.ShowBottomShort(WelcomeActivity.this,name);
        /**
         * 为uri添加参数
         */
        Uri.Builder builder = Uri.parse(uriString).buildUpon();
        builder.appendQueryParameter("id", "23");
        builder.appendQueryParameter("title", "红日集团");
        //ToastUtil.ShowBottomShort(WelcomeActivity.this, builder.query("title").toString());

        //替换参数值
        String uriString = replaceParameters(builder.build().toString(), "title", "红日总集团");
        //intent.setData(builder.build());

        intent.setData(Uri.parse(uriString));
        startActivity(intent);
        finish();

        /**
         * 以下为BroadcastReceiver测试
         */

        //        IntentFilter filter = new IntentFilter();
        //        filter.addAction(broadAction);
        //        receiver = new TestReceiver();
        //        registerReceiver(receiver,filter);
        //
        //        Intent intent = new Intent();
        //        intent.setAction(broadAction);
        //        sendBroadcast(intent);

        /**
         * 以下为service测试
         */
        //        service = new Intent(this, TestService.class);
        //        startService(service);
        //        bindService(intent_service,conn,BIND_AUTO_CREATE);

        /**
         * 以下为IntentService测试
         *
         * 经验证：
         * 启动多次，但IntentService的实例只有一个
         * 所以任务有IntentService中onHandleIntent方法排序处理
         */

        //        Logger.d("thread:"+ Thread.currentThread().getId());
        //        intentService = new Intent(this, TestIntentService.class);
        //        intentService.putExtra("name","hongri");
        //        startService(intentService);

        //intentService = new Intent(this, TestIntentService.class);
        //intentService.putExtra("name","hongri2");
        //startService(intentService);
        //
        //intentService.putExtra("name","hongri3");
        //startService(intentService);
        //
        //intentService.putExtra("name","hongri4");
        //startService(intentService);

        /**
         * 以下为startActivityForResult测试
         */
        //        Bundle bundle = new Bundle();
        //        bundle.putString("name","yao");
        //        bundle.putString("age","18");
        //        intent.putExtras(bundle);
        //        startActivityForResult(intent,requestCode);
        //        finish();
    }

    private String replaceParameters(String uri, String title, String value) {
        if (!TextUtils.isEmpty(uri) && !TextUtils.isEmpty(title)) {
            uri = uri.replaceAll("(" + title + "=[^&]*)", title + "=" + value);
        }
        return uri;
    }

    ServiceConnection conn = new ServiceConnection() {
        /**
         * ComponentName:
         * ComponentInfo{com.hongri.recyclerview/com.hongri.recyclerview.service.TestService}
         *
         * IBinder:
         * android.os.Binder@6e5de06
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Logger.d("onServiceConnected" + " ComponentName:" + name + " IBinder:" + service);
            testService = ((TestService.ServiceBinder)service).getService();
            testService.customMethod();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Logger.d("onServiceDisconnected");
            testService = null;
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        //        stopService(intent_service);
        //        if (conn != null){
        //            unbindService(conn);
        //        }

        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    //    @Override
    //    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //        super.onActivityResult(requestCode, resultCode, data);
    //
    //        Logger.d("onActivityResult");
    //
    //        if (requestCode == 0){
    //
    //            Logger.d("requestCode == 0");
    //
    //            if (resultCode == RESULT_OK){
    //
    //                String like = data.getStringExtra("like");
    //
    //                Logger.d("resultCode == RESULT_OK 返回上个Activity成功");
    //                Logger.d("返回数据成功--like:"+like);
    //            }
    //
    //        }else {
    //
    //            Logger.d("requestCode != 0");
    //
    //        }
    //
    //    }

    @Override
    public void method() {
        Logger.d("welcome--method");
    }
}
